package cn.controller;

import cn.entity.Goods;
import cn.entity.Orders;
import cn.entity.Ordersdetail;
import cn.entity.Users;
import cn.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
//@Scope("prototype")
@RequestMapping("/orders")
public class OrdersController {//SSM
    @Autowired
    OrdersService ordersService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    UsersService usersService;
    @Autowired
    CartsService cartsService;
    @Autowired
    OrdersdetailService ordersdetailService;
    @RequestMapping("admin/list")
    public String list(String ordersno, Model model){
        List<Orders> list=ordersService.find(null);
        for(Orders v:list) {
            if (v.getUid() != null) {
                Users users = usersService.selectByPrimaryKey(v.getUid());
                v.setUsers(users);
            }
        }
        model.addAttribute("ordersno", ordersno);
        model.addAttribute("list", list);
        return "admin/orders";
    }

    @RequestMapping("admin/detail/{id}")
    @ResponseBody
    public List<Ordersdetail> detail(@PathVariable Integer id){
        List<Ordersdetail> details=ordersdetailService.find(id);
        for(Ordersdetail od:details){
            if(od.getGid()!=null){
                Goods goods=goodsService.selectByPrimaryKey(od.getGid());
                od.setGoods(goods);
            }
        }
      return details;
    }

    @RequestMapping("admin/update")
    public String update(Integer id,String status)  {
            if("已发货".equals(status)){
                List<Ordersdetail> details=ordersdetailService.find(id);
                for(Ordersdetail od:details){
                    if(od.getGid()!=null){
                        Goods goods=goodsService.selectByPrimaryKey(od.getGid());
                        goods.setKucun(goods.getKucun()-od.getQuantity());
                        goods.setXiao(goods.getXiao()+od.getQuantity());
                        goodsService.updateByPrimaryKey(goods);
                    }
                }
            }
            Orders orders=ordersService.selectByPrimaryKey(id);
            orders.setStatus(status);
            int n=ordersService.updateByPrimaryKey(orders);
            return "redirect:/orders/admin/list";
        }



    @RequestMapping("admin/delete")
    public String  delete(Integer id) {
        Orders orders=ordersService.selectByPrimaryKey(id);
        orders.setIsdel(1);
        int n=ordersService.updateByPrimaryKey(orders);
        return "redirect:/orders/admin/list";
    }
}
